package com.zdzx.controller.web;

import java.awt.Color;
import java.awt.Font;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdzx.base.common.util.RedisUtil;
import com.zdzx.base.common.util.UserInfoUtil;
import com.zdzx.common.result.PageInfo;
import com.zdzx.common.result.PageUtil;
import com.zdzx.common.result.Result;
import com.zdzx.common.result.ResultCode;
import com.zdzx.common.result.ResultUtil;
import com.zdzx.mapper.CertificateMapper;
import com.zdzx.mapper.CertificateUserMapper;
import com.zdzx.mapper.CourseMapper;
import com.zdzx.mapper.CourseTestsMapper;
import com.zdzx.mapper.CourseUserTestsMapper;
import com.zdzx.mapper.UserMapper;
import com.zdzx.model.service.base.result.UserInfo;
import com.zdzx.model.service.base.vo.User;
import com.zdzx.model.service.content.param.SubmitTests;
import com.zdzx.model.service.content.vo.Certificate;
import com.zdzx.model.service.content.vo.CertificateUser;
import com.zdzx.model.service.content.vo.Course;
import com.zdzx.model.service.content.vo.CourseTests;
import com.zdzx.model.service.content.vo.CourseUserTests;
import com.zdzx.utils.ImageUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags = "web考试")
@RestController()
@RequestMapping("/web")
public class WebTestsController {
	

	@Autowired
	private CourseUserTestsMapper courseUserTestsMapper;
	@Autowired
	private CourseTestsMapper courseTestsMapper;
	@Autowired
	private CourseMapper courseMapper;
	@Autowired
	private CertificateMapper certificateMapper;
	@Autowired
	private CertificateUserMapper certificateUserMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private RedisUtil redisUtil;
	
	@ApiOperation(value = "用户考试记录", notes = "")
	@GetMapping("/course/tests")
	public Result<PageInfo<CourseUserTests>> course(
			@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
			@ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize,
			HttpServletRequest request){
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		if(loginInfo==null) {
			return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(),ResultCode.NOT_LOGIN.getMes(), null);
		}
		Page<CourseUserTests> page = new Page<>(pageNum == null ? 1 : pageNum, pageSize == null ? 10 : pageSize);
		
		IPage<CourseUserTests> info = courseUserTestsMapper.selectPageByCourse(page,loginInfo.getId());
		
		PageInfo<CourseUserTests> data = PageUtil.data(info.getPages(), info.getCurrent(), info.getTotal(), info.getRecords());
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, data);
	}
	
	@ApiOperation(value = "考试信息", notes = "")
	@GetMapping("/course/tests/{certificateId}")
	public Result<Certificate> getCertificateInfo(@PathVariable("certificateId")String certificateId,HttpServletRequest request){
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		if(loginInfo==null) {
			return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(),ResultCode.NOT_LOGIN.getMes(), null);
		}
		Certificate certificate = certificateMapper.selectById(certificateId);
		String courseIds = certificate.getCourseIds();
		List<Map> parseArray = JSON.parseArray(courseIds, Map.class);
		for (int i=0;i<parseArray.size();i++) {
			QueryWrapper<CourseUserTests> queryWrapper=new QueryWrapper<CourseUserTests>();
			queryWrapper.eq("course_id", parseArray.get(i).get("id"));
			queryWrapper.eq("user_id",loginInfo.getId());
			List<CourseUserTests> list = courseUserTestsMapper.selectList(queryWrapper);
			if(list!=null&&list.size()>0) {
				parseArray.get(i).put("mark", list.get(0).getMark().toString());
			}else {
				parseArray.get(i).put("mark", "0");
			}
			parseArray.set(i, parseArray.get(i));
		}
		certificate.setInfo(parseArray);
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, certificate);
	}
	
	@ApiOperation(value = "获取试题", notes = "") 
	@GetMapping("/course/tests/user/{courseId}") 
	public Result<Map<String,List<CourseTests>>> getTests(@PathVariable("courseId")String courseId,HttpServletRequest request){
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		if(loginInfo==null) {
			return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(),ResultCode.NOT_LOGIN.getMes(), null);
		}
		Course course = courseMapper.selectById(courseId);
		if(course==null) {
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "课程不存在！！！", null);
		}
		QueryWrapper<CourseTests> queryWrapper=new QueryWrapper<CourseTests>();
		queryWrapper.eq("course_id", courseId);
		List<CourseTests> list = courseTestsMapper.selectList(queryWrapper);
		Map<String,List<CourseTests>> map=new HashMap<String, List<CourseTests>>();
		List<CourseTests> d=new ArrayList<CourseTests>();
		List<CourseTests> s=new ArrayList<CourseTests>();
		for (CourseTests courseTests : list) {
			if("0".equals(courseTests.getType())) {
				d.add(courseTests);
			}else if("1".equals(courseTests.getType())) {
				s.add(courseTests);
			}
		}
		if(course.getDcount()==0) {
			d.clear();
		}else {
			int c=d.size()-course.getDcount();
			Random r=new Random();
			for (int i = 0; i < c; i++) {
				d.remove(r.nextInt((d.size()-i)<=0?1:d.size()-i));
			}
		}
		if(course.getScount()==0) {
			s.clear();
		}else {
			int c=s.size()-course.getScount();
			Random r=new Random();
			for (int i = 0; i < c; i++) {
				s.remove(r.nextInt((s.size()-i)<=0?1:s.size()-i));
			}
		}
		redisUtil.set(loginInfo.getId()+":"+courseId+":d",d ,60*60*3);
		redisUtil.set(loginInfo.getId()+":"+courseId+":s",s ,60*60*3);
		map.put("d", d);
		map.put("s", s);
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null,map);
	}
	
	
	
	
	@SuppressWarnings("unchecked")
	@ApiOperation(value = "提交试卷", notes = "") 
	@PostMapping("/course/tests/{courseId}") 
	public Result<List<CourseTests>> submitTests(@PathVariable("courseId")String courseId,@RequestBody SubmitTests submitTests,
			HttpServletRequest request){
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		if(loginInfo==null) {
			return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(),ResultCode.NOT_LOGIN.getMes(), null);
		}
		Course course = courseMapper.selectById(courseId);
		//QueryWrapper<CourseTests> queryWrapper=new QueryWrapper<CourseTests>();
		//queryWrapper.eq("course_id", courseId);
		//List<CourseTests> lists = courseTestsMapper.selectList(queryWrapper);
		Map<String,List<CourseTests>> map=new HashMap<String, List<CourseTests>>();
		List<CourseTests> d=new ArrayList<CourseTests>();
		List<CourseTests> s=new ArrayList<CourseTests>();
		d=(List<CourseTests>)redisUtil.get(loginInfo.getId()+":"+courseId+":d");
		s=(List<CourseTests>)redisUtil.get(loginInfo.getId()+":"+courseId+":s");
		/*for (CourseTests courseTests : lists) {
			if("0".equals(courseTests.getType())) {
				d.add(courseTests);
			}else if("1".equals(courseTests.getType())) {
				s.add(courseTests);//````````````````````````````````
			}
		}*/
		map.put("d", d);
		map.put("s", s);
		
		
		int count=course.getSumCount();
		int a=count/(d.size()+s.size());
		int err=0;
		for(int i=0;i<map.get("d").size();i++) {
			CourseTests courseTests = map.get("d").get(i);
			String answer = courseTests.getAnswer();
			String string = submitTests.getTestd().get(courseTests.getId());
			courseTests.setUserAnswer(string);
			map.get("d").set(i, courseTests);
			if(!answer.equals(string)) {
				count=count-a;
				err++;
			}
		}
		for(int i=0;i<map.get("s").size();i++) {
				CourseTests courseTests = map.get("s").get(i);
				String answer = courseTests.getAnswer();
				List<List<String>> tests = submitTests.getTests();
				String str="";
				for (String string : tests.get(i)) {
					str+=string;
				}
				
				courseTests.setUserAnswer(str);
				map.get("s").set(i, courseTests);
				if(!answer.equals(str)) {
					count=count-a;
					err++;
				}
			}
		QueryWrapper<CourseUserTests> queryWrapperUser=new QueryWrapper<CourseUserTests>();
		queryWrapperUser.eq("course_id", courseId);
		queryWrapperUser.eq("user_id", loginInfo.getId());
		List<CourseUserTests> userTestsList = courseUserTestsMapper.selectList(queryWrapperUser);
		if(userTestsList!=null&&userTestsList.size()>0) {
			CourseUserTests courseUserTests = userTestsList.get(0);
			courseUserTests.setTestsd(JSON.toJSONString(map.get("d")));
			courseUserTests.setTestss(JSON.toJSONString(map.get("s")));
			courseUserTests.setCreateTime(LocalDateTime.now());
			courseUserTests.setMark(count+"");
			courseUserTestsMapper.updateById(courseUserTests);
		}else {
			CourseUserTests courseUserTests=new CourseUserTests();
			courseUserTests.setUserId(loginInfo.getId());
			courseUserTests.setCourseTitle(course.getTitle());
			courseUserTests.setCourseId(courseId);
			courseUserTests.setCourseTitle(course.getTitle());
			courseUserTests.setMark(count+"");
			courseUserTests.setTestsd(JSON.toJSONString(map.get("d")));
			courseUserTests.setTestss(JSON.toJSONString(map.get("s")));
			courseUserTests.setCreateTime(LocalDateTime.now());
			courseUserTestsMapper.insert(courseUserTests);
		}
		d.addAll(s);
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null,d);
	}
	
	@ApiOperation(value = "获取用户试题", notes = "") 
	@GetMapping("/course/user/tests/{courseId}") 
	public Result<CourseUserTests> getUserTests(@PathVariable("courseId")String courseId,HttpServletRequest request){
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil,request);
		if(loginInfo==null) {
			return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(),ResultCode.NOT_LOGIN.getMes(), null);
		}
		QueryWrapper<CourseUserTests> queryWrapperUser=new QueryWrapper<CourseUserTests>();
		queryWrapperUser.eq("course_id", courseId);
		queryWrapperUser.eq("user_id", loginInfo.getId());
		List<CourseUserTests> userTestsList = courseUserTestsMapper.selectList(queryWrapperUser);
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null,userTestsList.size()>0?userTestsList.get(0):null);
	}
	
	@ApiOperation(value = "用户证书", notes = "")
	@GetMapping("/course/certificate")
	public Result<PageInfo<Certificate>> getCertificateList(
			@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
			@ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize,
			HttpServletRequest request){
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		if(loginInfo==null) {
			return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(),ResultCode.NOT_LOGIN.getMes(), null);
		}
		Page<Certificate> page = new Page<>(pageNum == null ? 1 : pageNum, pageSize == null ? 10 : pageSize);
		
		IPage<Certificate> info = certificateMapper.selectUserCertificatePage(page,loginInfo.getId());
		
		PageInfo<Certificate> data = PageUtil.data(info.getPages(), info.getCurrent(), info.getTotal(), info.getRecords());
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, data);
	}
	
	public static void main(String[] args) {
		Random r=new Random();
		
		
		for(int i=0;i<100;i++) {
			System.out.println(r.nextInt(11));
		}
	}
	
	
	@ApiOperation(value = "用户证书", notes = "")
	@PostMapping("/course/certificate/{certificateId}")
	public Result<PageInfo<Certificate>> applyCertificateList(@PathVariable("certificateId")String certificateId,
			HttpServletRequest request){
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		if(loginInfo==null) {
			return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(),ResultCode.NOT_LOGIN.getMes(), null);
		}
		Certificate selectById = certificateMapper.selectById(certificateId);
		
		if(selectById!=null) {
			String courseIds = selectById.getCourseIds();
			List<Map> parseArray = JSON.parseArray(courseIds, Map.class);
			boolean checkR=true;
			int sumMark=0;
			for (Map map : parseArray) {
				String id = map.get("id").toString();
				String name=map.get("name").toString();
				Course selectById2 = courseMapper.selectById(id);
				QueryWrapper<CourseUserTests> queryWrapper=new QueryWrapper<CourseUserTests>();
				queryWrapper.eq("course_id", id);
				List<CourseUserTests> selectList = courseUserTestsMapper.selectList(queryWrapper);
				if(selectById2==null) {
					return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "申请条件不够！！！", null);
				}else if(selectList==null||selectList.size()==0) {
					return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "申请条件不够！！！", null);
				}else if(Integer.parseInt(selectList.get(0).getMark())<Integer.parseInt(selectById.getMinMark())) {
					return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "申请条件不够！！！", null);
				}
				sumMark+=Integer.parseInt(selectList.get(0).getMark());
			}
			if(Integer.parseInt(selectById.getSumCount())>sumMark) {
				return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "申请条件不够！！！", null);
			}else {
				CertificateUser entity=new CertificateUser();
				entity.setUserId(loginInfo.getId());
				entity.setCertificateId(selectById.getId());
				entity.setCreateTime(LocalDateTime.now());
				certificateUserMapper.insert(entity);
				return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, null);
			}
		}
		return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "申请条件不够！！！", null);
	}
	
	
	@ApiOperation(value = "用户证书", notes = "")
	@GetMapping("/course/certificate/{certificateId}/{userId}")
	public void getCertificateList(@PathVariable("certificateId")String certificateId,
			@PathVariable("userId")String userId,
			HttpServletRequest request,HttpServletResponse response){
		User selectById2 = userMapper.selectById(userId);
		if(selectById2==null) {
			return;
		}
		QueryWrapper<CertificateUser> queryWrapper=new QueryWrapper<CertificateUser>();
		queryWrapper.eq("certificate_id", certificateId);
		queryWrapper.eq("user_id", selectById2.getId());
		List<CertificateUser> selectList = certificateUserMapper.selectList(queryWrapper);
		if(!selectList.isEmpty()) {
			Certificate selectById = certificateMapper.selectById(certificateId);
			String path = selectById.getPath();
			InputStream imageStream = getImageStream(path);
			if(imageStream!=null) {
				Font font = new Font("微软雅黑", Font.PLAIN, selectById.getFontSize());                     //水印字体
		        String srcImgPath="d:/222.jpg"; //源图片地址
		        String tarImgPath="D:/111.jpg"; //待存储的地址
		        String waterMarkContent=selectById2.getRealName();  //水印内容
		        Color color=new Color(0,0,0);                      
		        //水印图片色彩以及透明度
		        response.setHeader("Pragma", "No-cache");
				response.setHeader("Cache-Control", "no-cache");
				response.setDateHeader("Expires", 0);
				response.setContentType("image/jpg");
				response.setHeader("Content-Disposition", "attachment;fileName="+System.currentTimeMillis()+".jpg");
				int x=selectById.getX();
				int y=selectById.getY();
		       ImageUtil.addWaterMark(imageStream, waterMarkContent,color, font,x,y,response);
			}else {
				
			}
		}
		
		
	}
	public InputStream getImageStream(String url) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                return inputStream;
            }
        } catch (IOException e) {
            System.out.println("获取网络图片出现异常，图片路径为：" + url);
            e.printStackTrace();
        }
        return null;
    }
	
}	

